package Service;

import Dao.Impl.*;
import Model.*;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import Dao.*;
import Util.EmailSender;
import Util.ReportGenerator;
import Util.Utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class UserSystem {
    private static final Logger logger = LogManager.getLogger(UserSystem.class);
    private final UserDAO userDAO;
    private final TransactionDAO transactionDAO;
    private final FinancialProductDAO financialProductDAO;
    private final FinancialProductTaskDAO financialProductTaskDAO;
    private final Scanner scanner;
    private final ReportGenerator reportGenerator;
    private final Utils utils;

    public UserSystem(Connection connection) {
        this.reportGenerator = new ReportGenerator();
        this.userDAO = new UserDAOImpl();
        this.transactionDAO = new TransactionDAOImpl();
        this.financialProductDAO = new FinancialProductDAOImpl();
        this.financialProductTaskDAO = new FinancialProductTaskDAOImpl();
        this.scanner = new Scanner(System.in);
        utils = new Utils();
    }

    void userOperations(User user) throws SQLException {
        boolean loggedIn = true;

        while (loggedIn) {
            System.out.println("=========================");
            System.out.println("欢迎回来，" + user.getUsername() + "！");
            System.out.println(">主菜单>用户操作菜单");
            System.out.println("1. 账户交易");
            System.out.println("2. 查询账户余额");
            System.out.println("3. 查询交易记录");
            System.out.println("4. 理财产品管理");
            System.out.println("5. 导出交易记录");
            System.out.println("6. 修改密码");
            System.out.println("0. 退出");
            System.out.println("=========================");
            System.out.print("请选择操作(0-6): ");

            int input = getValidMenuChoice(6);

            if (input == 0){
                System.out.println(user.getUsername() + " 已退出登录。");
                loggedIn = false;
                continue;
            }

            if (user.isFrozen() == 1) {
                System.out.println("您的账户已被冻结，无法进行操作。请联系管理员解冻。");
                continue;
            }

            switch (input) {
                case 1:
                    userTransactions(user);
                    user = userDAO.getUsrByName(user.getUsername());
                    break;
                case 2:
                    getUserDataByName(user.getUsername());
                    break;
                case 3:
                    getUserTransactions(user);
                    break;
                case 4:
                    financialProductUser(user);
                    break;
                case 5:
                    reportGenerator.generateTransactionHistoryReport(user);
                    break;
                case 6:
                    changePassword(user);
                    user = userDAO.getUsrByName(user.getUsername());
                    break;
                default:
                    System.out.println("无效的选择，请重新输入。");
                    break;
            }
        }
    }

    private void changePassword(User user) {
        try {
            logger.info("用户 {} 正在修改密码。", user.getUsername());

            // 生成验证码
            String verificationCode = utils.generateVerificationCode();
            LocalDateTime verificationCodeExpiry = LocalDateTime.now().plusMinutes(30); // 验证码有效期 30 分钟

            // 发送验证码邮件
            sendPasswordChangeVerificationEmail(user, verificationCode);

            // 提示用户输入验证码
            System.out.print("请输入验证码：");
            String input = scanner.nextLine();
            while (input.isEmpty()) {
                System.out.print("验证码不能为空，请重新输入：");
                input = scanner.nextLine();
            }

            // 验证验证码
            if (input.equals(verificationCode) && LocalDateTime.now().isBefore(verificationCodeExpiry)) {
                // 验证成功，提示用户输入新密码
                System.out.print("验证码正确！请输入新密码：");
                String newPassword = scanner.nextLine();

                // 检查密码复杂度
                if (!utils.isValidPassword(newPassword)) {
                    System.out.println("密码必须包含至少 8 个字符，且包含字母和数字。");
                    return;
                }

                // 更新用户密码
                user.setPassword(newPassword);
                userDAO.updateUser(user);
                logger.info("用户 {} 的密码已更新。", user.getUsername());

                // 发送密码修改成功邮件
                sendPasswordChangeSuccessEmail(user);

                System.out.println("密码修改成功，确认邮件已发送至您的邮箱。");

            } else {
                // 验证码错误或过期
                if (LocalDateTime.now().isAfter(verificationCodeExpiry)) {
                    System.out.println("验证码已过期，请重新请求验证码。");
                } else {
                    System.out.println("验证码不正确，请重新输入(如果未收到邮件请联系管理员或检查邮箱是否正确)。");
                }
            }
        } catch (SQLException e) {
            logger.error("数据库操作时出错: {}", e.getMessage());
        }
    }

    private void sendPasswordChangeVerificationEmail(User user, String verificationCode) {
        // 构建验证码邮件正文
        String body = "亲爱的 " + user.getUsername() + "，\n\n"
                + "您正在请求修改密码。请使用以下验证码完成操作：\n\n"
                + "验证码：" + verificationCode + "\n\n"
                + "请在 30 分钟内使用此验证码完成密码修改。\n\n"
                + "如果您没有请求修改密码，请忽略此邮件。\n\n"
                + "感谢您的使用！\n"
                + "SimpleBank 团队";

        // 发送验证码到用户邮箱
        EmailSender.sendEmail(user.getContactInfo(), "SimpleBank 密码修改验证码", body);
        logger.info("已向用户 {} 发送验证码邮件。", user.getUsername());
    }

    private void sendPasswordChangeSuccessEmail(User user) {
        // 构建密码修改成功邮件正文
        String successBody = "亲爱的 " + user.getUsername() + "，\n\n"
                + "您的密码已成功修改。\n\n"
                + "如果您没有进行此操作，请立即联系我们的客服团队。\n\n"
                + "感谢您的使用！\n"
                + "SimpleBank 团队";

        // 发送密码修改成功邮件
        EmailSender.sendEmail(user.getContactInfo(), "SimpleBank 密码修改成功", successBody);
        logger.info("已向用户 {} 发送密码修改成功邮件。", user.getUsername());
    }

    private void userTransactions(User user) {
        boolean running = true;
        while (running) {
            System.out.println("=========================");
            System.out.println(">主菜单>用户操作菜单>账户交易");
            System.out.println("1. 存款");
            System.out.println("2. 取款");
            System.out.println("3. 转账");
            System.out.println("0. 返回上一级");
            System.out.println("=========================");
            System.out.print("请选择操作(0-3): ");

            int input = getValidMenuChoice(3);

            switch (input) {
                case 1:
                    try {
                        depositUser(user);
                        user = userDAO.getUsrByName(user.getUsername());
                    } catch (SQLException e) {
                        System.out.println("存款时出错: " + e.getMessage());
                    }
                    break;
                case 2:
                    try {
                        withdraw(user);
                        user = userDAO.getUsrByName(user.getUsername());
                    } catch (SQLException e) {
                        System.out.println("取款时出错: " + e.getMessage());
                    }
                    break;
                case 3:
                    transfer(user);
                    try {
                        user = userDAO.getUsrByName(user.getUsername());
                    } catch (SQLException e) {
                        logger.error("获取用户信息时出错: {}", e.getMessage());
                    }
                    break;
                case 0:
                    running = false;
                    break;
                default:
                    System.out.println("无效的选择，请重新输入。");
                    break;
            }
        }
    }

    public void depositUser(User user) {
        try {
            double amount;
            while (true) {
                System.out.print("请输入存款金额: ");
                if (scanner.hasNextDouble()) {
                    String input = scanner.next();
                    scanner.nextLine();

                    if (input.matches("^\\d+(\\.\\d{1,2})?$")) {
                        amount = Double.parseDouble(input);
                        if (amount <= 0) {
                            System.out.println("存款金额必须大于0，请重新输入。");
                        } else {
                            break;
                        }
                    } else {
                        System.out.println("输入格式错误，金额小数点后只能有两位数字，请重新输入。");
                    }
                } else {
                    System.out.println("输入格式错误，请输入一个有效的数字。");
                    scanner.nextLine();
                }
            }

            if (user.getBalance() > Double.MAX_VALUE - amount) {
                System.out.println("存款金额过大，会导致余额溢出。");
                return;
            }

            System.out.print("输入存款备注(可选): ");
            String remark = scanner.nextLine().trim();

            user.setBalance(user.getBalance() + amount);
            userDAO.updateUser(user);
            Transaction transaction = new Transaction();
            transaction.setUserId(user.getId());
            transaction.setTransactionType("存款");
            transaction.setAmount(amount);
            transaction.setTotalBalance(user.getBalance());
            transaction.setDescription(remark);
            transactionDAO.addTransaction(transaction);

            System.out.println("存款成功，当前余额为: " + user.getBalance());
        } catch (SQLException e) {
            System.out.println("存款时出错: " + e.getMessage());
        }
    }

    public void withdraw(User user) {
        try {
            System.out.print("请输入取款金额: ");
            double amount = scanner.nextDouble();
            scanner.nextLine();

            if (amount > user.getBalance()) {
                System.out.println("余额不足，当前余额为: " + user.getBalance());
                return;
            }

            user.setBalance(user.getBalance() - amount);
            userDAO.updateUser(user);

            System.out.print("输入存款备注(可选): ");
            String remark = scanner.nextLine().trim();

            Transaction transaction = new Transaction();
            transaction.setUserId(user.getId());
            transaction.setTransactionType("取款");
            transaction.setAmount(amount);
            transaction.setTotalBalance(user.getBalance());
            transaction.setDescription(remark);
            transactionDAO.addTransaction(transaction);

            System.out.println("取款成功，当前余额为: " + user.getBalance());
        } catch (SQLException e) {
            logger.error("取款时出错: {}", e.getMessage());
        }
    }

    private void transfer(User user) {
        try {
            System.out.print("请输入收款人姓名: ");
            String recipientName = scanner.nextLine().trim();
            while (recipientName.isEmpty()) {
                System.out.print("收款人姓名不能为空，请重新输入: ");
                recipientName = scanner.nextLine().trim();
            }

            User recipient = userDAO.getUsrByName(recipientName);
            if (recipient == null) {
                System.out.println("收款人不存在。");
                return;
            }

            System.out.print("请输入转账金额: ");
            double amount;
            while (true) {
                if (scanner.hasNextDouble()) {
                    String input = scanner.next();
                    scanner.nextLine();

                    if (input.matches("^\\d+(\\.\\d{1,2})?$")) {
                        amount = Double.parseDouble(input);
                        if (amount <= 0) {
                            System.out.println("转账金额必须大于0，请重新输入。");
                        } else {
                            break;
                        }
                    } else {
                        System.out.println("输入格式错误，金额小数点后只能有两位数字，请重新输入。");
                    }
                } else {
                    System.out.println("输入格式错误，请输入一个有效的数字。");
                    scanner.nextLine();
                }
            }

            if (amount > user.getBalance()) {
                System.out.println("余额不足，当前余额为: " + user.getBalance());
                return;
            }

            user.setBalance(user.getBalance() - amount);
            recipient.setBalance(recipient.getBalance() + amount);

            userDAO.updateUser(user);
            userDAO.updateUser(recipient);

            System.out.print("输入转账备注(可选): ");
            String remark = scanner.nextLine().trim();

            Transaction transaction = new Transaction();
            transaction.setUserId(user.getId());
            transaction.setTransactionType("转账");
            transaction.setAmount(amount);
            transaction.setTotalBalance(user.getBalance());
            transaction.setDescription(remark);
            transactionDAO.addTransaction(transaction);

            Transaction recipientTransaction = new Transaction();
            recipientTransaction.setUserId(recipient.getId());
            recipientTransaction.setTransactionType("收款");
            recipientTransaction.setAmount(amount);
            recipientTransaction.setTotalBalance(recipient.getBalance());
            recipientTransaction.setDescription(remark);
            transactionDAO.addTransaction(recipientTransaction);

            System.out.println("转账成功，当前余额为: " + user.getBalance());
        } catch (SQLException e) {
            logger.error("转账时出错: {}", e.getMessage());
        }
    }

    private void getUserTransactions(User user) {
        try {
            List<Transaction> transactions = transactionDAO.getTransactionsByUserId(user.getId());
            if (transactions.isEmpty()) {
                System.out.println("未找到交易记录");
            } else {
                System.out.println(">主菜单>用户操作菜单>查询交易记录");
                System.out.println(user.getUsername()+" 交易记录:");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+----------------------+");
                System.out.printf("| %-15s | %-20s | %-20s | %-20s | %-20s |\n", "TransactionType", "Amount", "Total Balance", "Transaction Date", "Description");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+----------------------+");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                for (Transaction transaction : transactions) {
                    System.out.printf("| %-15s | %-20.2f | %-20.2f | %-20s | %-20s |\n",
                            transaction.getTransactionType(),
                            transaction.getAmount(),
                            transaction.getTotalBalance(),
                            dateFormat.format(transaction.getTransactionDate()),
                            transaction.getDescription());
                }
                System.out.println("+-----------------+----------------------+----------------------+----------------------+----------------------+");
            }
        } catch (SQLException e) {
            logger.error("查询交易记录时出错: {}", e.getMessage());
        }
    }

    private int getValidMenuChoice(int num) {
        int input = 0;
        boolean validInput = false;

        while (!validInput) {
            try {
                input = scanner.nextInt();
                scanner.nextLine();
                if (input >= 0 && input <= num) {
                    validInput = true;
                } else {
                    System.out.println("无效的选择，请输入0到" + num + "之间的数字。");
                    System.out.print("请重新选择操作(0-" + num + "): ");
                }
            } catch (InputMismatchException e) {
                System.out.println("无效的输入，请输入一个整数。");
                System.out.print("请重新选择操作(0-" + num + "): ");
                scanner.next();
            }
        }
        return input;
    }

    private void getUserDataByName(String username) {
        try {
            User user = userDAO.getUsrByName(username);
            if (user != null) {
                System.out.println(">主菜单>用户操作菜单>查询账户余额");
                System.out.println("Account balance information:");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                System.out.printf("| %-15s | %-20s | %-20s | %-20s |\n", "user", "pwd", "phone", "balance");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                System.out.printf("| %-15s | %-20s | %-20s | %-20.2f |\n", user.getUsername(), user.getPassword(), user.getContactInfo(), user.getBalance());
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
            } else {
                System.out.println("用户不存在。");
            }
        } catch (SQLException e) {
            logger.error("查询用户信息时出错: {}", e.getMessage());
        }
    }

    private void financialProductUser(User user) {
        boolean running = true;

        while (running) {
            System.out.println("=========================");
            System.out.println(">主菜单>用户操作菜单>理财产品管理");
            System.out.println("1. 购买理财产品");
            System.out.println("2. 取消理财服务");
            System.out.println("3. 查询已购买的理财产品");
            System.out.println("4. 查看已购买理财产品的预期收益");
            System.out.println("0. 返回上一级");
            System.out.println("=========================");
            System.out.print("请选择操作(0-4): ");

            int input = getValidMenuChoice(4);

            switch (input) {
                case 1:
                    purchaseFinancialProduct(user);
                    break;
                case 2:
                    cancelFinancialProduct(user);
                    break;
                case 3:
                    queryPurchasedFinancialProducts(user);
                    break;
                case 4:
                    viewExpectedReturns(user);
                    break;
                case 0:
                    running = false;
                    break;
                default:
                    System.out.println("无效的选择，请重新输入。");
                    break;
            }
        }
    }

    private void cancelFinancialProduct(User user) {
        try {
            List<UserFinancialProduct> userFinancialProducts = userDAO.getUserFinancialProducts(user.getId());

            if (userFinancialProducts.isEmpty()) {
                System.out.println("你没有购买任何理财产品，无法取消。");
                return;
            }

            // 创建一个包含下标的列表
            List<UserFinancialProduct> indexedUserFinancialProducts = new ArrayList<>(userFinancialProducts);

            System.out.println("你的已购买理财产品：");
            for (int i = 0; i < indexedUserFinancialProducts.size(); i++) {
                UserFinancialProduct ufp = indexedUserFinancialProducts.get(i);
                FinancialProduct product = financialProductDAO.getFinancialProductById(ufp.getProductId());
                System.out.println("理财产品编号: " + (i + 1)); // 下标从1开始
                System.out.println("理财产品ID: " + ufp.getProductId());
                System.out.println("理财产品名称: " + product.getName());
                System.out.println("购买金额: " + ufp.getPurchaseAmount());
                System.out.println("状态: " + ufp.getStatus());
                System.out.println("----------------------------");
            }

            System.out.print("请输入要取消的理财产品编号: ");
            int productIndexToCancel = scanner.nextInt();

            if (productIndexToCancel < 1 || productIndexToCancel > indexedUserFinancialProducts.size()) {
                System.out.println("无效的理财产品编号，取消操作失败。");
                return;
            }

            UserFinancialProduct productToCancel = indexedUserFinancialProducts.get(productIndexToCancel - 1);

            // 直接删除
            userDAO.deleteUserFinancialProduct(productToCancel.getId());

            // 退还本金
            user.setBalance(user.getBalance() + productToCancel.getPurchaseAmount());
            userDAO.updateUser(user);

            // 添加交易记录
            Transaction transaction = new Transaction();
            transaction.setUserId(user.getId());
            transaction.setTransactionType("取消理财产品");
            transaction.setAmount(productToCancel.getPurchaseAmount());
            transaction.setTotalBalance(user.getBalance());
            transaction.setDescription("取消理财产品: " + productToCancel.getProductId());
            transactionDAO.addTransaction(transaction);

            // 删除Task任务
            financialProductTaskDAO.deleteFinancialProductTask(productToCancel.getId());

            System.out.println("理财产品取消成功，退还金额: " + productToCancel.getPurchaseAmount() + "，当前余额为: " + user.getBalance());

        } catch (SQLException e) {
            logger.error("取消理财产品时出错: {}", e.getMessage());
        }
    }

    private void queryPurchasedFinancialProducts(User user) {
        try {
            List<UserFinancialProduct> userFinancialProducts = userDAO.getUserFinancialProducts(user.getId());

            if (userFinancialProducts.isEmpty()) {
                System.out.println("你没有购买任何理财产品。");
                return;
            }

            System.out.println("你的理财产品：");
            for (UserFinancialProduct ufp : userFinancialProducts) {
                FinancialProduct product = financialProductDAO.getFinancialProductById(ufp.getProductId());
                System.out.println("理财产品名称: " + product.getName());
                System.out.println("描述: " + product.getDescription());
                System.out.println("年化利率: " + product.getInterestRate() + "%");
                System.out.println("购买金额: " + ufp.getPurchaseAmount());
                System.out.println("购买日期: " + ufp.getPurchaseDate());
                System.out.println("----------------------------");
            }
        } catch (SQLException e) {
            logger.error("查询已购买的理财产品时出错: {}", e.getMessage());
        }
    }

    private void viewExpectedReturns(User user) {
        try {
            List<UserFinancialProduct> userFinancialProducts = userDAO.getUserFinancialProducts(user.getId());

            if (userFinancialProducts.isEmpty()) {
                System.out.println("你没有购买任何理财产品。");
                return;
            }

            System.out.println("你的理财产品及预期收益：");
            for (UserFinancialProduct ufp : userFinancialProducts) {
                int productId = ufp.getProductId();
                FinancialProduct product = financialProductDAO.getFinancialProductById(productId);
                System.out.println("理财产品名称: " + product.getName());
                System.out.println("购买金额: " + ufp.getPurchaseAmount());
                System.out.println("预期收益: " + ufp.getExpectedEarnings());
                System.out.println("---------------------------");
            }
        } catch (SQLException e) {
            logger.error("查看预期收益时出错: {}", e.getMessage());
        }
    }

    private void purchaseFinancialProduct(User user) {
        showFinancialProducts();
        System.out.print("选择要购买的理财产品ID: ");
        int selectedProductId = scanner.nextInt();

        try {
            FinancialProduct selectedProduct = financialProductDAO.getFinancialProductById(selectedProductId);
            if (selectedProduct == null || !selectedProduct.getIsActive()) {
                System.out.println("选中的理财产品不存在或已下架。");
                return;
            }

            System.out.println("你选择的理财产品: ");
            System.out.println("名称: " + selectedProduct.getName());
            System.out.println("描述: " + selectedProduct.getDescription());
            System.out.println("年化利率: " + selectedProduct.getInterestRate() + "%");

            System.out.print("请输入购买金额: ");
            double purchaseAmount = scanner.nextDouble();

            if (purchaseAmount == 0) {
                System.out.println("购买金额不能为0!");
                return;
            }

            if (purchaseAmount > user.getBalance()) {
                System.out.println("账户余额不足，无法购买该理财产品。");
                return;
            }

            user.setBalance(user.getBalance() - purchaseAmount);
            userDAO.updateUser(user);

            double expectedEarnings = purchaseAmount * selectedProduct.getInterestRate() / 100;

            UserFinancialProduct userFinancialProduct = new UserFinancialProduct();
            userFinancialProduct.setUserId(user.getId());
            userFinancialProduct.setProductId(selectedProduct.getId());
            userFinancialProduct.setPurchaseAmount(purchaseAmount);
            userFinancialProduct.setStatus("ACTIVE");
            userFinancialProduct.setExpectedEarnings(expectedEarnings);

            if (userFinancialProduct.getPurchaseDate() == null) {
                userFinancialProduct.setPurchaseDate(new Timestamp(new Date().getTime()));
            }

            userDAO.addUserFinancialProduct(userFinancialProduct);

            FinancialProductTask task = new FinancialProductTask();
            task.setUserId(user.getId());
            task.setProductId(selectedProduct.getId());
            task.setPurchaseAmount(purchaseAmount);
            task.setExpectedEarnings(expectedEarnings);
            task.setPurchaseDate(new Timestamp(new Date().getTime()));

            // 获取当前时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.YEAR, 1);

            task.setMaturityDate(new Timestamp(calendar.getTimeInMillis())); // 计算到期时间
            task.setStatus("PENDING");
            financialProductTaskDAO.addFinancialProductTask(task); // 插入任务

            Transaction transaction = new Transaction();
            transaction.setUserId(user.getId());
            transaction.setTransactionType("购买理财产品");
            transaction.setAmount(purchaseAmount);
            transaction.setTotalBalance(user.getBalance());
            transaction.setDescription("购买理财产品: " + selectedProduct.getName());
            transactionDAO.addTransaction(transaction);

            // 在成功购买理财产品后调用
            sendFinancialProductPurchaseNotification(user, selectedProduct, userFinancialProduct);
            System.out.println("购买成功，当前余额为: " + user.getBalance());
        } catch (SQLException e) {
            logger.error("购买理财产品时出错: {}", e.getMessage());
        }
    }

    private void sendFinancialProductPurchaseNotification(User user, FinancialProduct selectedProduct, UserFinancialProduct userFinancialProduct) {
        try {
            logger.info("用户 {} 购买理财产品 {} 成功，准备发送通知邮件。", user.getUsername(), selectedProduct.getName());

            String body = "亲爱的 " + user.getUsername() + "，\n\n"
                    + "恭喜您成功购买理财产品！\n\n"
                    + "产品详情：\n"
                    + "产品名称：" + selectedProduct.getName() + "\n"
                    + "购买金额：" + String.format("%.2f", userFinancialProduct.getPurchaseAmount()) + " 元\n"
                    + "年化利率：" + selectedProduct.getInterestRate() + "%\n"
                    + "预计收益：" + String.format("%.2f", userFinancialProduct.getExpectedEarnings()) + " 元\n"
                    + "购买日期：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(userFinancialProduct.getPurchaseDate()) + "\n"
                    + "感谢您选择SimpleBank理财服务！\n"
                    + "如有任何疑问，请联系我们的客服团队。\n\n"
                    + "SimpleBank 团队";

            EmailSender.sendEmail(user.getContactInfo(), "SimpleBank 理财产品购买成功通知", body);
            logger.info("已向用户 {} 发送理财产品购买成功邮件。", user.getUsername());
        } catch (Exception e) {
            logger.error("发送理财产品购买通知邮件时出错: {}", e.getMessage());
        }
    }

    private void showFinancialProducts() {
        try {
            List<FinancialProduct> products = financialProductDAO.getAllFinancialProducts();
            if (products.isEmpty()) {
                System.out.println("还没有保存的理财产品。");
            } else {
                System.out.println("FinancialProduct information:");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                System.out.printf("| %-15s | %-20s | %-20s | %-20s |\n", "产品ID", "产品名称", "年化利率(%)", "状态");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                for (FinancialProduct product : products) {
                    System.out.printf("| %-15d | %-20s | %-20.2f | %-20s |\n",
                            product.getId(),
                            product.getName(),
                            product.getInterestRate(),
                            product.getIsActive() ? "已上架" : "已下架");
                    System.out.println("产品描述: " + product.getDescription());
                    System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                }
            }
        } catch (SQLException e) {
            logger.error("获取理财产品列表时出错: {}", e.getMessage());
        }
    }
}